package learn.juc;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.StampedLock;

public class StampedSample {

    private final StampedLock lock = new StampedLock();

    private static List list = new ArrayList();

    void mutate() {
        long stamp = lock.writeLock();
        try {
            list.add(1);
            Thread.sleep(1000*600);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlockWrite(stamp);
        }
    }

    int access() {
        long stamp = lock.tryOptimisticRead();
        int data = (int) list.get(0);
        if (!lock.validate(stamp)) {
            stamp = lock.readLock();
            try {
                data = (int) list.get(0);
            } finally {
                lock.unlockWrite(stamp);
            }
        }
        return data;
    }

    public static void main(String[] args) throws InterruptedException {
        StampedSample test = new StampedSample();
        Thread t1 = new Thread(() -> test.mutate());
        Thread t2 = new Thread(() -> test.access());
        t1.start();
//        t1.join();
        t2.start();
    }

}
